package cn.player.adapter;

import java.util.List;

import net.tsz.afinal.FinalBitmap;
import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONObject;

import android.animation.IntEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.animation.ValueAnimator.AnimatorUpdateListener;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import cn.player.App;
import cn.player.R;
import cn.player.entity.ChannelInfo;
import cntv.player.engine.Const;
import cntv.player.core.util.Utils;
import cn.player.media.adapter.BaseAdpt;
import cn.player.media.util.DateUtil;

/**
 * 频道信息列表adpater
 * @author zengliang
 *
 */
public class ChannelInfoAdapter2 extends BaseAdpt<ChannelInfo> {
	
	private App app;
	private FinalBitmap finalBitamp;
	private FinalHttp finalHttp;
	private int lastPosition;
	

	public ChannelInfoAdapter2(Context mContext, List<ChannelInfo> mData,int layoutResource) {
		super(mContext, mData, layoutResource);
		// TODO Auto-generated constructor stub
		app = (App) mContext.getApplicationContext();
		finalBitamp = app.getFinalBitmap();
		finalHttp = app.getFinalHttp();
	}
	
	@Override
	protected void addViewId() {
		// TODO Auto-generated method stub
		mViewIds.add(R.id.iv_channel_image);
		mViewIds.add(R.id.iv_channel_icon);
		mViewIds.add(R.id.tv_channel_name);
		mViewIds.add(R.id.tv_channel_live_title);
		mViewIds.add(R.id.pb_live_run_progress);
	}
	
	@Override
	protected void animationShow(int position,View convertView) {
		// TODO Auto-generated method stub
		super.animationShow(position,convertView);
		
		Animation animation = AnimationUtils.loadAnimation(mContext, (position > lastPosition) ? R.anim.base_push_down_in : R.anim.base_push_up_in);
		convertView.startAnimation(animation);
	    lastPosition = position;
		
	}

	@Override
	protected void updateItemViews(int position) {
		// TODO Auto-generated method stub
		ImageView iv_channel_img = (ImageView) viewHolder.getView(R.id.iv_channel_image);
		ImageView iv_channel_icon = (ImageView) viewHolder.getView(R.id.iv_channel_icon);
		TextView tv_channel_name = (TextView) viewHolder.getView(R.id.tv_channel_name);
		TextView tv_channel_live_title = (TextView) viewHolder.getView(R.id.tv_channel_live_title);
		ProgressBar pb_live = (ProgressBar) viewHolder.getView(R.id.pb_live_run_progress);
		
		ChannelInfo info = mData.get(position);
		if(Utils.strToLong(info.getAutoImg()) == 1){
			String autoImgUrl = app.getBaseUrls().get(Const.KEY_AUTOIMG_URL).getUrl() + info.getChannelId() + "_01.png" + "?rdm=null";
			finalBitamp.display(iv_channel_img, autoImgUrl);
		}else{
			finalBitamp.display(iv_channel_img, info.getImgUrl());
		}
		finalBitamp.display(iv_channel_icon, info.getChannelImg());
		tv_channel_name.setText(info.getTitle());
		if(info.isReady()){
			tv_channel_live_title.setText(info.getPlayTitle());
			pb_live.setProgress(info.getPlayProgress());
//			setPropertyAnimation(position,pb_live, info.getPlayProgress());
		}else{
			getChannelPlayLiveInfo(position);
		}
		
	}
	
	/**
	 * 获取频道正在直播的相关信息并更新列表
	 * @param position
	 */
	private void getChannelPlayLiveInfo(final int position){
		if(mData == null || mData.get(position) == null){
			return;
		}
		String infoUrl = app.getBaseUrls().get(Const.KEY_LIVING_URL).getUrl() + "&c=" + mData.get(position).getChannelId();
		finalHttp.get(infoUrl, new AjaxCallBack<String>(){

			@Override
			public void onStart() {
				// TODO Auto-generated method stub
				super.onStart();
			}

			@Override
			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				super.onSuccess(result);
				try {
					JSONObject data = new JSONObject(result);
					
					
//					tvPlay.setText(data.optString("t"));
					 
					long currentTime = System.currentTimeMillis();
					String sStaTime = DateUtil.getTimeString(currentTime) + " " + data.optString("s").trim();//组装成 yyyyMMdd HH:mm:ss 格式日期
					String sEndTime = DateUtil.getTimeString(currentTime) + " " + data.optString("e").trim();//组装成 yyyyMMdd HH:mm:ss 格式日期
					long startTime = DateUtil.getMilliseconds(sStaTime, Const.DATE_TYPE_YMDHMS);
					long endTime = DateUtil.getMilliseconds(sEndTime, Const.DATE_TYPE_YMDHMS);
					int progress;
					if(currentTime <= startTime){
						progress = 0;
					}else if(currentTime >= endTime){
						progress = 100;
					}else{
						progress = (int) ((float)(currentTime - startTime)/(endTime - startTime)*100);
					}
//					setPropertyAnimation(pbProgress, progress);
					
					mData.get(position).setPlayTitle(data.optString("t"));
					mData.get(position).setPlayProgress(progress);
					mData.get(position).setReady(true);
					
					notifyDataSetChanged();
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(Throwable t, int errorNo, String strMsg) {
				// TODO Auto-generated method stub
				super.onFailure(t, errorNo, strMsg);
			}
			
		});
	}
	
	@SuppressLint("NewApi")
	private void setPropertyAnimation(final int position, final ProgressBar progressBar, final int progress) {
		if (android.os.Build.VERSION.SDK_INT >= 11 && !mData.get(position).isAnim() && progress != 0) {
			ValueAnimator anim = ObjectAnimator.ofInt(0, progress);
			anim.setDuration(1000);
			anim.addUpdateListener(new AnimatorUpdateListener() {

				@Override
				public void onAnimationUpdate(ValueAnimator animation) {
					progressBar.setProgress((Integer)animation.getAnimatedValue());
					if((Integer)animation.getAnimatedValue() == progress){
						mData.get(position).setAnim(true);
					}
				}
			});
			anim.setEvaluator(new IntEvaluator());
			anim.start();
		} else {
			progressBar.setProgress(progress);
		}
	}
	

}
